package com.lerays.spider.sougou.handler;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.lionsoul.websnail.json.JSONObject;

import com.lerays.spider.sougou.SpiderHttpServer;
import com.lerays.spider.sougou.hack.Session;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * @author dongyado<dongyado@gmail.com>
 */
public class SessionAddRequestHandler implements HttpHandler
{
	private SpiderHttpServer httpServer = null;
	
	public SessionAddRequestHandler( SpiderHttpServer httpServer )
	{
		this.setHttpServer(httpServer);
	}

	@Override
	public void handle(HttpExchange e) throws IOException 
	{
		//get the request body
		StringBuilder sb = new StringBuilder();
		BufferedInputStream bis = new BufferedInputStream(e.getRequestBody());
		int chr = 0;
		while ( (chr = bis.read()) != -1 )
		{
			sb.append((char)chr);
		}
		
		//parse the outuncoming setting json
		JSONObject json = new JSONObject(sb.toString());
		JSONObject rets = new JSONObject();
		
		// wechat session 
		//check and set the user agent
		String username, refererUrl, checkUrl, cookies, syncUrl, userAgent;
		
		if ( json.has("username") && (username = json.getString("username")) != null
			 && json.has("refererUrl") && (refererUrl = json.getString("refererUrl")) != null
			 && json.has("checkUrl") && (checkUrl = json.getString("checkUrl")) != null
			 && json.has("cookies") && (cookies = json.getString("cookies")) != null
			 && json.has("syncUrl") && (syncUrl = json.getString("syncUrl")) != null
			 && json.has("userAgent") && (userAgent = json.getString("userAgent")) != null )
		{
			/*System.out.println("username: "+username+", refererUrl: "+refererUrl
					+", checkUrl: "+checkUrl+", cookies: "+cookies+", syncUrl: "
					+syncUrl+", userAgent: "+userAgent);*/
			httpServer.getsougouSpider().getSessionFactory().add(new Session(
				username, refererUrl, checkUrl, cookies, syncUrl, userAgent
			));
			rets.put("add", true);
		} 
		else
		{
			rets.put("add", false);
		}
		
		//send the http response
		String ret = rets.toString();
		e.sendResponseHeaders(200, ret.length());
		OutputStream os = e.getResponseBody();
		os.write(ret.getBytes());
		os.close();
		e.close();
		
		//let gc do its work
		bis.close();
		sb = null;
	}

	public SpiderHttpServer getHttpServer() 
	{
		return httpServer;
	}

	public void setHttpServer(SpiderHttpServer httpServer) 
	{
		this.httpServer = httpServer;
	}
}
